package com.SoftwareManage.shiro;

import com.SoftwareManage.entity.User;
import com.SoftwareManage.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;


//自定义realm
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    /**
     * doGetAuthorizationInfo
     * 执行授权逻辑
     * 获取权限信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取当前用户
        User user= (User) principalCollection.getPrimaryPrincipal();
        String username=user.getUsername();
        //获取当前用户角色
        Set<String> roles=userService.getRolesByUsername(username);
        if (roles !=null && roles.size()>0){
            //添加角色
            info.addRoles(roles);
        }
        //获取当前用户权限
        Set<String> perms=userService.findPermByUsername(username);
        //添加资源的授权字符串
        if(perms != null && perms.size() > 0){
            //授权
            info.addStringPermissions(perms);
        }
        return info;
    }

    /**
     * doGetAuthenticationInfo
     * 执行认证逻辑
     * 获取认证信息
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //编写shiro判断逻辑，判断用户名和密码
        //1.判断用户名
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        User user=userService.findByUsername(token.getUsername());//从数据库中根据用户名查找实体
        if (user==null){
            //用户名不存在
            throw new UnknownAccountException(); // 账号不存在;//shiro底层会抛出UnKnowAccountException
        }else if (user.getStatus().equals("禁用")){
            throw new LockedAccountException();//账号被锁定
        }else{
        }
        //2.判断密码
        //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配
        //SimpleAuthenticationInfo(principal, hashedCredentials, credentialsSalt, realmName);
        //其中principal是账号信息(会传给权限认证)，hashedCredentials是MD5加密后的密码，
        // credentialsSalt是密码加密的盐值，realmName为当前realm对象的name。

        //对于盐值credentialsSalt，在Shiro中为org.apache.shiro.util.ByteSource对象：
        //ByteSource credentialsSalt = ByteSource.Util.bytes("");
        //ByteSource提供了一个内部方法，可以将字符串转换为对应的盐值信息。
        return new SimpleAuthenticationInfo(user,user.getPassword(), ByteSource.Util.bytes(user.getSalt()),this.getName());
    }
}

